<?php
class Vote extends CI_Model{
	public $user_id;
	public $petition_id;
	public $vote_time;
	public $user;
	public $petition;
	
	public function mapResultToVote($data){
		$vote = new Vote();
		$vote->user_id = $data->user_id;
		$vote->petition_id = $data->petition_id;
		$vote->vote_time = $data->vote_time;
		get_instance()->load->model('users/user');
		get_instance()->load->model('petitions/petition');
		$vote->user = get_instance()->user->getUserByID($vote->user_id);
		$vote->petition = get_instance()->petition->getPetition($vote->petition_id);

		return $vote;
	}
	
	public function recentVoteView($list){
		$return ="";
		foreach($list as $vote){

			$return .= $vote->mapVoteToHTML();

		}
		return $return;
	}
	
	public function returnVotesAfterDate($last){
		$list = get_instance()->db->query('SELECT * FROM petition_vote WHERE vote_time > ?', array($last))->result();
		if (count($list) == 0) return false;
		$result = array();
		foreach($list as $vote){
			$return[] = $vote->mapVoteToHTML();
		}
		return $result;
	}
	
	public function mapVoteToHTML(){	
		$data['vote'] = $this;
		return get_instance()->load->view('common/recent_vote_li', $data, TRUE);
	}
	
	public function getLastVotes($count = 10){
		@$return = @get_instance()->db->query('SELECT * FROM petition_vote ORDER BY vote_time DESC LIMIT ?', array($count))->result();
		
		$result = array();
		foreach($return as $row){
			 $result[] = $this->mapResultToVote($row);
		}
		//var_dump($result);
		return $this->recentVoteView($result);
	}
	
	public function howLongAgo(){
		$when = time()-strtotime($this->vote_time);
		if ( $when > 60*60*24*30*12) $return =(int) ($when / (60*60*24*30*12)) .  ' year';
		else if ($when >= 60*60*24*31) $return = (int) ($when / (60*60*24*31)) .  ' month';
		else if ($when >= 60*60*24) $return = (int)($when / (60*60*24)) . ' day';
		else if ($when >= 60*60) $return = (int)( $when / (60*60)) . ' hour';
		else if ($when >= 60) $return = (int)( $when / (60)). ' minute';
		else $return = (int) ($when) . 'second';
		if ($return != 1) $return .= 's';
		return $return;
	}
}